package com.cta.view.controller;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cta.service.ProfileService;
import com.cta.utils.RequestUtils;

@Controller
public class HomeController extends BasicController {

	private final static String PBX_FACTORY = "PBX_FACTORY";
	private final static String SERVICE_PROVIDER = "SERVICE_PROVIDER";
	
	private final static String PBX = "PBX";
	private final static String TRUNK = "TRUNK";
	private final static String USER = "USER";
	
	@Autowired
	private ProfileService profileService;
	
	@RequestMapping(value = {"/","/index"}, method = RequestMethod.GET)
	public String index() {
		if(RequestUtils.isSuperAdmin()){
			return "redirect:/admin";
		} else {
			return "redirect:/user";
		}
		
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "login";
	}
	
	@RequestMapping(value="/loginfailed", method = RequestMethod.GET)
	public String loginerror(ModelMap model) {
 
		model.addAttribute("error", "true");
		return "login";
 
	}
	
	@RequestMapping(value = "/admin", method = RequestMethod.GET)
	public String admin() {
		return "admin";
	}
	
	@RequestMapping(value = "/user", method = RequestMethod.GET)
	public String user() {
		return "user";
	}
	
	@RequestMapping(value = "/checkname", method = RequestMethod.GET)
	public @ResponseBody String checkName(String name, String checkOn) {
		try {
			if(StringUtils.isNotEmpty(checkOn)){
				boolean hasName = false;
				if(PBX_FACTORY.equals(checkOn)) {
					hasName = profileService.hasPBXFactoryName(name);
				} else if(SERVICE_PROVIDER.equals(checkOn)){
					hasName = profileService.hasServiceProviderName(name);
				} else if(PBX.equals(checkOn)){
					hasName = profileService.hasPBXName(name);
				}  else if(TRUNK.equals(checkOn)){
					hasName = profileService.hasTrunkName(name);
				} else if(USER.equals(checkOn)){
					hasName = profileService.hasUserName(name);
				} else {
					return String.format("{'success':false, msg:'%s'}","CheckOn not match");
				}
				if(hasName) {
					return String.format("{'success': false, msg:'%s'}","This name is exist, please choose another name.");
				} else {
					return String.format("{'success': true}");
				}
			} else {
				return String.format("{'success':false, msg:'%s'}","Check on can not emtpy string");
			}
		} catch (Exception e) {
			log.error("Error: ", e);
			return String.format("{'success':false, msg:'%s'}", e.getMessage());
		}
	}
}
